<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/3/28
 * Time: 14:21
 */

namespace app\admin\controller;


use app\admin\model\RoleModel;
use app\admin\model\RuleModel;
use think\Request;

class Role extends Base
{
    protected $roleModel;
    protected $ruleModel;

    /*
     * 依赖注入Model
     * */
    public function __construct(RoleModel $roleModel,RuleModel $ruleModel){
        parent::__construct();
        $this->roleModel = $roleModel;
        $this->ruleModel = $ruleModel;
    }

    /*
     * 角色列表
     * */
    public function role_index(){
        $this->assign("data",$this->roleModel->listAll());
        return $this->fetch('role/index');
    }

    /*
    * 新增角色
    * */
    public function role_add(){
        if(Request::instance()->isPost()){
            $validate=$this->roleModel->validate_model('add');
            if ($validate['code']){
                return $this->roleModel->add();
            }else{
                return $validate;
            }
        }
        return $this->fetch('role/add');
    }

    /*
    * 修改角色
    * */
    public function role_edit(){
        if(Request::instance()->isPost()){
            $validate=$this->roleModel->validate_model('edit');
            if ($validate['code']){
                return $this->roleModel->edit();
            }else{
                return $validate;
            }
        }
        $id=input('get.id/d');
        $this->assign("data",$this->roleModel->getById($id));
        return $this->fetch('role/edit');
    }

    /*
    * 删除角色
    * */
    public function role_del(){
        return $this->roleModel->del();
    }

    /*
     * 权限分配
     * */
    public function role_authority(){
        if(Request::instance()->isPost()){
            $validate=$this->ruleModel->validate_model();
            if ($validate['code']){
                return $this->ruleModel->auth();
            }else{
                return $validate;
            }
        }
        $role_id=input("get.role_id/s");
        $role_rule=$this->ruleModel->getByRoleId($role_id);
        $has_pers=[];
        foreach($role_rule as $value){
            $has_per=$value["controller"]."-".$value["action"];
            array_push($has_pers,$has_per);
        }unset($value);
        $this->assign("role_id",$role_id);
        $this->assign("has_pers",json_encode($has_pers));
        $this->assign("role_name",$this->roleModel->getByMaps(['role_id'=>$role_id])->name);
        $this->assign("authorityArr",Base::getAuthorityList());
        return $this->fetch('role/authority');
    }

}